<template>
    <div class="loan-list">
        <h2>贷款利息计算器</h2>

        <el-card>
            <el-descriptions
                :column="4"
                :content-style="{width: '15%'}"
                :label-style="{lineHeight: '32px'}"
                border
                size="medium"
                title="贷款信息">
                <template slot="extra">
                    <el-button
                        :size="size"
                        type="primary"
                        @click="basicInfoVisible = !basicInfoVisible">
                        {{ basicInfoVisible ? '保存' : '编辑' }}
                    </el-button>
                </template>
                <el-descriptions-item label="贷款总额">
                    <el-input
                        v-if="basicInfoVisible"
                        v-model="basicInfo.loanAmount"
                        :size="size"
                        placeholder="请输入贷款总额（元）"
                        type="number">
                        <template v-slot:append>元</template>
                    </el-input>
                    <span v-else>{{ basicInfo.loanAmount }} 元</span>
                </el-descriptions-item>
                <el-descriptions-item label="贷款年限">
                    <el-select
                        v-if="basicInfoVisible"
                        v-model="basicInfo.loanYears"
                        :size="size">
                        <el-option
                            v-for="item in loadYearOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <span v-else>{{ basicInfo.loanYears }} 年</span>
                </el-descriptions-item>
                <el-descriptions-item label="还款方式">
                    <el-select
                        v-if="basicInfoVisible"
                        v-model="basicInfo.repaymentType"
                        :size="size">
                        <el-option
                            v-for="item in repaymentTypeOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value" />
                    </el-select>
                    <span v-else>{{ repaymentTypeName }}</span>
                </el-descriptions-item>
                <el-descriptions-item v-if="isPrincipal" label="每月还款本金">
                    {{ principalRepayment }} 元
                </el-descriptions-item>
                <el-descriptions-item v-if="isInterest" label="每月还款利息">
                    <b>剩余本金 × (年利率 / 12)</b>
                </el-descriptions-item>
                <el-descriptions-item label="每月还款日期">
                    <el-date-picker
                        v-if="basicInfoVisible"
                        v-model="basicInfo.repaymentDate"
                        :size="size"
                        format="dd"
                        placeholder="选择还款日期"
                        type="date"
                        value-format="dd" />
                    <span v-else>每月的 {{ basicInfo.repaymentDate }} 日</span>
                </el-descriptions-item>
                <el-descriptions-item label="首次还款日期">
                    <el-date-picker
                        v-if="basicInfoVisible"
                        v-model="basicInfo.repaymentStartDate"
                        :size="size"
                        placeholder="选择还款年月"
                        type="date"
                        value-format="yyyy-MM-dd" />
                    <span v-else>{{ basicInfo.repaymentStartDate }}</span>
                </el-descriptions-item>
                <el-descriptions-item label="结束还款日期">
                    {{ repaymentEndDate }}
                </el-descriptions-item>
            </el-descriptions>
        </el-card>

        <el-card>
            <el-descriptions size="medium" title="利率设置">
                <template slot="extra">
                    <el-button
                        :size="size"
                        type="primary"
                        @click="handleAddRateRow">
                        添加
                    </el-button>
                </template>
            </el-descriptions>
            <el-table
                :data="rateList"
                border
                stripe>
                <el-table-column
                    align="center"
                    label="开始日期"
                    prop="startDate">
                    <template v-slot="{row}">
                        <el-date-picker
                            v-model="row.startDate"
                            format="yyyy年MM月"
                            type="date"
                            value-format="yyyy-MM" />
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="结束日期"
                    prop="endDate">
                    <template v-slot="{row}">
                        <el-date-picker
                            v-model="row.endDate"
                            format="yyyy年MM月"
                            type="month"
                            value-format="yyyy-MM" />
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="年利率（%）"
                    prop="rate">
                    <template v-slot="{row}">
                        <el-input
                            v-model="row.rate"
                            placeholder="请输入年利率"
                            type="number" />
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="操作"
                    width="80">
                    <template v-slot="{$index}">
                        <el-button
                            v-if="rateList.length > 1"
                            :size="size"
                            type="text"
                            @click="handleRemoveRateRow($index)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-card>
            <el-descriptions size="medium" title="提前还款设置">
                <template slot="extra">
                    <el-button
                        :size="size"
                        type="primary"
                        @click="handleAddPrepayment">
                        添加
                    </el-button>
                </template>
            </el-descriptions>
            <el-table
                :data="prepaymentList"
                border
                stripe>
                <el-table-column
                    align="center"
                    label="还款金额（元）"
                    prop="amount">
                    <template v-slot="{row}">
                        <el-input
                            v-model="row.amount"
                            placeholder="请输入还款金额"
                            type="number" />
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="还款时间"
                    prop="repaymentDate">
                    <template v-slot="{row}">
                        <el-date-picker
                            v-model="row.repaymentDate"
                            placeholder="选择还款时间"
                            type="date"
                            value-format="yyyy-MM-dd"
                            @change="handleUpdatePrepaymentMonth(row)" />
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="对应期数"
                    prop="month"
                    width="100">
                    <template v-slot="{row}">
                        <span>{{ row.month || '-' }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="还款方式"
                    prop="type">
                    <template v-slot="{row}">
                        <el-radio-group v-model="row.type" size="small">
                            <el-radio label="shorten">缩短期限</el-radio>
                            <el-radio label="reduce">减少月供</el-radio>
                        </el-radio-group>
                    </template>
                </el-table-column>
                <el-table-column
                    align="center"
                    label="操作"
                    width="80">
                    <template v-slot="{$index}">
                        <el-button
                            size="small"
                            type="text"
                            @click="handleRemovePrepayment($index)">删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <el-card>
            <el-descriptions size="medium" title="还款明细">
                <template slot="extra">
                    <el-button
                        :size="size"
                        type="primary"
                        @click="handleCalculate">
                        计算
                    </el-button>
                </template>
            </el-descriptions>
            <el-table
                :data="repaymentTable.data"
                :default-sort="{prop: 'month', order: 'ascending'}"
                border
                style="width: 100%; margin-top: 15px;">
                <el-table-column
                    label="期数"
                    prop="period"
                    align="center">
                    <template v-slot="{row}">
                        <span v-if="row.period">第{{ row.period }}期</span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="还款日期"
                    prop="date"
                    align="center" />
                <el-table-column
                    label="应还本金"
                    prop="principal"
                    header-align="center"
                    align="right" />
                <el-table-column
                    label="应还利息"
                    prop="interest"
                    header-align="center"
                    align="right" />
                <el-table-column
                    label="应还月供"
                    prop="amount"
                    header-align="center"
                    align="right" />
                <el-table-column
                    align="center"
                    label="年利率(%)"
                    prop="yearRate" />
                <el-table-column
                    label="剩余本金"
                    prop="remaining"
                    header-align="center"
                    align="right" />
            </el-table>
        </el-card>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import moment from 'moment';
import { BasicForm, PrepaymentInfo, RateInfo } from '@/types/loan';
import { REPAYMENT_TYPE_OPTIONS } from '@/consts/loan';
import { cloneDeep } from 'lodash';

const DEFAULT_BASIC_INFO: Partial<BasicForm> = {
    loanAmount: 1000000,
    loanYears: 30,
    repaymentDate: '27',
    repaymentStartDate: '2024-04-27',
    repaymentType: 'principal',
};

const DEFAULT_RATE_LIST: RateInfo[] = [
    { startDate: '2024-01', endDate: '2024-12', rate: 3.1 },
    { startDate: '2025-01', endDate: '2025-12', rate: 2.85 },
    { startDate: '2026-01', endDate: '', rate: 2.6 },
];

@Component
export default class LoanList extends Vue {
    size = 'small';
    basicInfo: Partial<BasicForm> = cloneDeep(DEFAULT_BASIC_INFO);
    rateList: RateInfo[] = cloneDeep(DEFAULT_RATE_LIST);
    prepaymentList: PrepaymentInfo[] = [];
    repaymentTable = {
        data: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
    };
    basicInfoVisible = false;
    loadYearOptions = [
        { value: 5, label: '5年' },
        { value: 10, label: '10年' },
        { value: 15, label: '15年' },
        { value: 20, label: '20年' },
        { value: 30, label: '30年' },
    ];
    repaymentTypeOptions = REPAYMENT_TYPE_OPTIONS;

    get loanYears(): number {
        return this.basicInfo.loanYears || 0;
    }

    // 初始还款总期数
    get totalPeriod(): number {
        return this.loanYears * 12;
    }

    get isPrincipal(): boolean {
        return this.basicInfo.repaymentType === REPAYMENT_TYPE_OPTIONS.PRINCIPAL.value;
    }

    get isInterest(): boolean {
        return this.basicInfo.repaymentType === REPAYMENT_TYPE_OPTIONS.INTEREST.value;
    }

    get principalRepayment(): number {
        return parseFloat((this.basicInfo.loanAmount / this.loanYears / 12).toFixed(2));
    }

    get repaymentEndDate() {
        return moment(this.basicInfo.repaymentStartDate).add(this.loanYears, 'years').format('YYYY-MM-DD');
    }

    get repaymentTypeName() {
        return Object.values(REPAYMENT_TYPE_OPTIONS)?.find(item => item.value === this.basicInfo.repaymentType)?.label || '';
    }

    handleAddRateRow(): void {
        this.rateList.push({
            startDate: '',
            endDate: '',
            rate: 0
        });
    }

    handleRemoveRateRow(index: number): void {
        if (this.rateList.length > 1) {
            this.rateList.splice(index, 1);
        }
    }

    handleAddPrepayment(): void {
        this.prepaymentList.push({
            amount: 0,
            date: '',
            period: 0,
            type: 'shorten'
        });
    }

    handleRemovePrepayment(index: number): void {
        if (this.prepaymentList.length > 0) {
            this.prepaymentList.splice(index, 1);
        }
    }

    // 主计算函数，整合所有计算逻辑
    async handleCalculate(): Promise<void> {
        try {
            // 利率设置
            const validRates = this.rateList.filter(period => period.startDate && period.rate > 0);
            if (validRates.length === 0) {
                this.$message.error('请至少设置一个有效的浮动利率期间');
                return;
            }

            let repaymentType = this.basicInfo.repaymentType;
            console.log('还款方式', repaymentType);
            if (this.isInterest) {
                // 等额本息还款明细
                this.handleCalculateInterestDetail();
            } else if (this.isPrincipal) {
                // 等额本金还款明细
                this.handleCalculatePrincipalDetail();
            }
        } catch (error) {
            console.error(error);
        }
    }

    // 还款明细
    handleCalculateInterestDetail() {
        try {
            console.log('计算等额本息还款明细');
        } catch (error) {
            console.error(error);
        }
    }

    handleCalculatePrincipalDetail() {
        try {
            let loanAmount = this.basicInfo.loanAmount || 0;
            if (loanAmount === 0) {
                return;
            }
            // TODO 判断是否存在提前还款 && 还款方式是缩短期限
            this.repaymentTable.data = [];
            let startDate = this.basicInfo.repaymentStartDate;
            // 待还本金
            const principal = this.principalRepayment;
            for (let i = 0; i < this.totalPeriod; i++) {
                // 还款时间
                const date = moment(startDate).add(i, 'months').format('YYYY-MM-DD');
                // 还款期数
                const period = i + 1;
                // 月利率
                let yearRate = this.handleGetYearRate(date);
                // 待还利息
                const interest = parseFloat((loanAmount * yearRate / 12 / 100).toFixed(2));
                // 还款金额
                const amount = parseFloat((principal + interest).toFixed(2));
                // 剩余本金
                if (loanAmount < principal) {
                    loanAmount = 0;
                } else {
                    loanAmount = parseFloat((loanAmount - principal).toFixed(2));
                }
                this.repaymentTable.data.push({
                    period, date, amount, principal, interest, yearRate, remaining: loanAmount
                });
            }
        } catch (error) {
            console.error(error);
        }
    }

    // 计算提前还款对应的期数
    handleCalculatePeriod(date: string): number {
        if (!date || !this.basicInfo.repaymentStartDate) return 0;

        const startMoment = moment(this.basicInfo.repaymentStartDate, 'YYYY-MM');
        const repayMoment = moment(date, 'YYYY-MM');

        // 计算从开始日期到提前还款日期的月数差
        const monthDiff = repayMoment.diff(startMoment, 'months') + 1;

        return Math.max(1, monthDiff);
    }

    // 根据利率设置信息和指定时间获取实际年利率值
    handleGetYearRate(date: string = moment().format('YYYY-MM')): number {
        if (!this.rateList || this.rateList.length === 0) {
            return 0;
        }

        const targetDate = moment(date, 'YYYY-MM');

        // 遍历利率列表，找到当前时间对应的利率
        for (const rateItem of this.rateList) {
            if (!rateItem.startDate || !rateItem.rate) continue;

            const startDate = moment(rateItem.startDate, 'YYYY-MM');
            let endDate = null;

            if (rateItem.endDate) {
                endDate = moment(rateItem.endDate, 'YYYY-MM');
            }

            // 检查是否在当前利率区间内
            if (targetDate.isSameOrAfter(startDate)) {
                // 如果有结束日期且当前日期在结束日期之后，跳过
                if (endDate && targetDate.isAfter(endDate)) {
                    continue;
                }

                return rateItem.rate;
            }
        }

        // 如果当前时间不在任何利率区间内，返回第一个利率或默认利率
        return this.rateList[0]?.rate;
    }
}
</script>

<style lang="scss" scoped>
.loan-list {
  width: 100%;
  padding: 0 20px 20px;
  box-sizing: border-box;

  h2 {
    text-align: center;
  }

  .el-select,
  .el-date-editor {
    width: 100%;
  }

  .el-descriptions-item__label {
    align-items: center;
  }

  .el-card:not(:last-child) {
    margin-bottom: 20px;
  }

  .el-pagination {
    margin-top: 10px;
    text-align: right;
  }
}
</style>
